package com.rice.riceaiagent.advisor;


import org.springframework.ai.chat.client.advisor.api.*;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义 ReReading Advisor
 * @author ricejson
 */
public class MyReReadingAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {
    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        return -1;
    }

    /**
     * 实现ReReading逻辑
     * @return 返回ReReading之后的请求
     */
    private AdvisedRequest reReading(AdvisedRequest advisedRequest) {
        Map<String, Object> userParams = new HashMap<>(advisedRequest.userParams());
        // 设置替换模板
        userParams.put("input_prompt", advisedRequest.userText());
        return AdvisedRequest.from(advisedRequest)
                .userText("""
                        {input_prompt}
                        reading the question again: {input_prompt}
                        """)
                .userParams(userParams)
                .build();
    }

    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        return chain.nextAroundCall(reReading(advisedRequest));
    }

    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        return chain.nextAroundStream(reReading(advisedRequest));
    }
}
